﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CongregacaoOs.Data;
using CongregacaoOs.Business;

namespace CongregacaoOs.WebForm.Cadastros
{
    public partial class Adm : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["DadosGerais"] == null) Response.Redirect("~/Cadastros/Account/Login.aspx");

            if (Session["TipoUsuario"].ToString() == "Local") Response.Redirect("~/Cadastros/Home.aspx");

            Page.Form.DefaultButton = btnBuscar.UniqueID;

            if (!IsPostBack )
            {
                AtualizaGridView();
                AtualizarSetores();
                AtualizarDropDowListRegional();
                AtualizarDropRegionalFiltro();
            }

            hfIndexAccordion.Value = "0";
        }

        public void AtualizaGridView()
        {
            ccAdmBus bus = new ccAdmBus();
            ccAdm ent = new ccAdm();

            ent.nome = txtBuscarNome.Text;
            ent.idAdm = 0;
            ent.idRegional = dropRegionalFiltro.SelectedValue != "" ? Convert.ToInt32(dropRegionalFiltro.SelectedValue): 0;
            ent.idDistrital = dropDistritalFiltro.SelectedValue != "" ? Convert.ToInt32(dropDistritalFiltro.SelectedValue) : 0; ;
            gvAdministracao.DataSource = bus.AdmSelect(ent);
            gvAdministracao.DataBind();
        }

        public void AtualizarSetores()
        {
            ccSetorBus bus = new ccSetorBus();
            ccSetor ent = new ccSetor();

            listSetores.DataSource = bus.SetorSelect(ent);
            listSetores.DataBind();


        }

        public void AtualizarDropDowListRegional(int aID = 0)
        {
            ccRegionalBus bus = new ccRegionalBus();
            ccRegional ent = new ccRegional();
            dropRegional.DataSource = bus.RegionalSelect(ent);
            dropRegional.DataBind();
        }

        public void AtualizarDropDowListDistrital()
        {
            ccDistritalBus bus = new ccDistritalBus();
            ccDistrital ent = new ccDistrital();

            ent.idRegional = dropRegional.SelectedValue != "" ? Convert.ToInt32(dropRegional.SelectedValue) : 0;
            dropDistrital.DataSource = bus.DistritalSelect(ent);
            dropDistrital.DataBind();
        }

        public void AtualizarDropRegionalFiltro()
        {
            using (ccRegionalBus bus = new ccRegionalBus())
            {
                ccRegional ent = new ccRegional();
                ent.nome = "";
                ent.idPais = 0;
                ent.idEstado = 0;
                ent.idRegional = 0;
                dropRegionalFiltro.DataSource = bus.RegionalSelect(ent);
                dropRegionalFiltro.DataBind();
            }

        }

        public void AtualizarDropDistritalFiltro()
        {
            using (ccDistritalBus bus = new ccDistritalBus())
            {
                ccDistrital ent = new ccDistrital();

                if (dropRegionalFiltro.SelectedValue != "")
                {
                    ent.idRegional = Convert.ToInt32(dropRegionalFiltro.SelectedValue);
                    dropDistritalFiltro.DataSource = bus.DistritalSelect(ent);
                    dropDistritalFiltro.DataBind();
                }
                else
                {
                    dropDistritalFiltro.Items.Clear();
                }

            }
        }


        #region Moving Itens in ListBox

        private void MoverItems(bool isAdd)
        {
            if (isAdd) //means if you add items to the right box
            {
                for (int i = listSetores.Items.Count - 1; i >= 0; i--)
                {
                    if (listSetores.Items[i].Selected)
                    {
                        listSetoresResult.Items.Add(listSetores.Items[i]);
                        listSetoresResult.ClearSelection();
                        listSetores.Items.Remove(listSetores.Items[i]);
                    }
                }
            }
            else // means if you remove items from the right box and add it back to the left box
            {
                for (int i = listSetoresResult.Items.Count - 1; i >= 0; i--)
                {
                    if (listSetoresResult.Items[i].Selected)
                    {
                        listSetores.Items.Add(listSetoresResult.Items[i]);
                        listSetores.ClearSelection();
                        listSetoresResult.Items.Remove(listSetoresResult.Items[i]);
                    }
                }
            }
        }

        private void MoveAllItems(bool isAddAll)
        {
            if (isAddAll) //means if you add ALL items to the right box
            {
                for (int i = listSetores.Items.Count - 1; i >= 0; i--)
                {
                    listSetoresResult.Items.Add(listSetores.Items[i]);
                    listSetoresResult.ClearSelection();
                    listSetores.Items.Remove(listSetores.Items[i]);
                }
            }
            else // means fi you remove all items from the right box and add it back to the left box 
            {
                for (int i = listSetoresResult.Items.Count - 1; i >= 0; i--)
                {
                    listSetores.Items.Add(listSetoresResult.Items[i]);
                    listSetores.ClearSelection();
                    listSetoresResult.Items.Remove(listSetoresResult.Items[i]);
                }
            }
        }

        #endregion    Moving Itens in ListBox

        protected void gvAdministracao_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            AtualizaGridView();
            gvAdministracao.PageIndex = e.NewPageIndex;
            gvAdministracao.DataBind();
        }

        protected void btnBuscar_Click(object sender, EventArgs e)
        {
            if (txtBuscarNome.Text != "")
                AtualizaGridView();
            else
            {
                AtualizaGridView();
            }
        }

        protected void gvAdministracao_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton imgEditar = (e.Row.FindControl("imgEditar") as ImageButton);
                imgEditar.CommandArgument = e.Row.RowIndex.ToString();

                ImageButton imgDelete = (e.Row.FindControl("imgDelete") as ImageButton);
                imgDelete.CommandArgument = e.Row.RowIndex.ToString();

                imgDelete.Attributes.Add("onclick", "javascript:return " +
                        "confirm('Confirmar exclusão do registro: " +
                        DataBinder.Eval(e.Row.DataItem, "Adm") + "?')");
            }
        }

        protected void gvAdministracao_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "EDITAR" || e.CommandName == "EXCLUIR")
            {
                
                int index = int.Parse(e.CommandArgument.ToString());
                hdID.Value = gvAdministracao.Rows[index].Cells[1].Text.Trim();


                HiddenField hdRegional = (gvAdministracao.Rows[index].FindControl("hdRegional") as HiddenField);
                HiddenField hdDistrital = (gvAdministracao.Rows[index].FindControl("hdDistrital") as HiddenField);

                if (e.CommandName == "EDITAR")
                {
                    hfIndexAccordion.Value = "1";
                    txtNome.Text = gvAdministracao.Rows[index].Cells[2].Text.Trim();

                    AtualizarDropDowListRegional();
                    if (hdRegional.Value != "") dropRegional.Items.FindByText(hdRegional.Value).Selected = true;
                    AtualizarDropDowListDistrital();
                    if (hdDistrital.Value != "") dropDistrital.Items.FindByText(hdDistrital.Value).Selected = true;

                    ccSetorBus admsetorBus = new ccSetorBus();
                    ccSetor admsetorEnt = new ccSetor();
                    
                    List<ccSetor> listResult;
                    listResult = admsetorBus.SetorSelect(Convert.ToInt32(hdID.Value));

                    if (listResult != null)
                        for (int i = listResult.Count - 1; i >= 0; i--)
                        {

                            listSetoresResult.Items.Add(new ListItem(listResult[i].nome, listResult[i].idSetor.ToString()));
                            listSetoresResult.ClearSelection();
                            listSetores.Items.Remove(new ListItem(listResult[i].nome, listResult[i].idSetor.ToString()));

                        }

                }
                else if (e.CommandName == "EXCLUIR")
                {
                    ccAdmSetorBus setorBus = new ccAdmSetorBus();
                    setorBus.AdmSetorDeleteByAdm(Convert.ToInt32(gvAdministracao.Rows[index].Cells[1].Text.Trim()));

                    ccAdmBus bus = new ccAdmBus();
                    bus.AdmDelete(Convert.ToInt32(gvAdministracao.Rows[index].Cells[1].Text.Trim()));
                    AtualizaGridView();
                }
            }
        }

        protected void btnAdicionarNovo_Click(object sender, EventArgs e)
        {
            hdID.Value = null;
            hfIndexAccordion.Value = "1";
            AtualizarSetores();
            AlinharCampos();                        
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {

            try
            {
                ccAdmBus bus = new ccAdmBus();
                ccAdm ent = new ccAdm();

                ent.nome = txtNome.Text.Trim();
                ent.idAdm = hdID.Value != "" ? Convert.ToInt32(hdID.Value) : 0;


                ent.idRegional = dropRegional.SelectedValue != "" ? Convert.ToInt32(dropRegional.SelectedValue) : 0;
                ent.idDistrital = dropDistrital.SelectedValue != "" ? Convert.ToInt32(dropDistrital.SelectedValue) : 0;


                int lIdAdm = bus.AdmSaveOrUpdate(ent);

                ccAdmSetorBus setorBus = new ccAdmSetorBus();
                ccAdmSetor setorEnt = new ccAdmSetor();

                if (hdID.Value != "") setorBus.AdmSetorDeleteByAdm(Convert.ToInt32(hdID.Value));


                for (int i = listSetoresResult.Items.Count - 1; i >= 0; i--)
                {
                    setorEnt.idSetor = Convert.ToInt32(listSetoresResult.Items[i].Value);
                    setorEnt.idAdm = lIdAdm != 0 ? lIdAdm : Convert.ToInt32(hdID.Value);
                    setorBus.AdmSetorSaveOrUpdate(setorEnt);
                }

                hfIndexAccordion.Value = "0";
                AtualizaGridView();
                AtualizarSetores();
                AlinharCampos();

                MessageWindow.MessageType = true;
                MessageWindow.Texto = "Registro salvo com sucesso!!!";
                MessageWindow.ShowWindow();
            }
            catch (Exception error)
            {

                MessageWindow.MessageType = false;
                MessageWindow.Texto = "Houve um erro ao salvar o registro. Tente novamente ou contate o suporte!!!"+error.Message;
                MessageWindow.ShowWindow();
            }
              
            
        }

        protected void btnVoltar_Click(object sender, EventArgs e)
        {
            hfIndexAccordion.Value = "0";
            listSetoresResult.Items.Clear();
            txtNome.Text = "";
            if (dropRegional.Items.Count > 0) dropRegional.SelectedIndex = 0;
            if (dropDistrital.Items.Count > 0) dropDistrital.SelectedIndex = 0;
        }



        protected void btnAdd_Click(object sender, EventArgs e)
        {
            MoverItems(true);
            hfIndexAccordion.Value = "1";
        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {
            MoverItems(false);
            hfIndexAccordion.Value = "1";
        }

        protected void btnAddAll_Click(object sender, EventArgs e)
        {
            MoveAllItems(true);
            hfIndexAccordion.Value = "1";
        }

        protected void btnRemoveAll_Click(object sender, EventArgs e)
        {
            MoveAllItems(false);
            hfIndexAccordion.Value = "1";
        }

        protected void dropRegional_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDowListDistrital();
            hfIndexAccordion.Value = "1";
        }

        protected void dropRegional_DataBound(object sender, EventArgs e)
        {
            dropRegional.Items.Insert(0, new ListItem("Escolha a Regional", String.Empty));
        }

        protected void dropDistrital_DataBound(object sender, EventArgs e)
        {
            dropDistrital.Items.Insert(0, new ListItem("Escolha a Distrital", String.Empty));
        }


        public void AlinharCampos() 
        {
            Functions.LimparCampos(this);
            if (dropRegional.Items.Count > 0) dropRegional.SelectedIndex = 0;
            if (dropDistrital.Items.Count > 0) dropDistrital.SelectedIndex = 0;
            listSetoresResult.Items.Clear();
            dropDistrital.Items.Clear();
        }

        protected void dropRegionalFiltro_DataBound(object sender, EventArgs e)
        {
            dropRegionalFiltro.Items.Insert(0, new ListItem("Escolha a Regional", String.Empty));
        }

        protected void dropRegionalFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizarDropDistritalFiltro();
            AtualizaGridView();
        }

        protected void dropDistritalFiltro_SelectedIndexChanged(object sender, EventArgs e)
        {
            AtualizaGridView();
        }

        protected void dropDistritalFiltro_DataBound(object sender, EventArgs e)
        {
            dropDistritalFiltro.Items.Insert(0, new ListItem("Escolha a Distrital", String.Empty));
        }
    }
}